package com.geniusk.system.service.impl;

import com.geniusk.common.enums.ResponseType;
import com.geniusk.common.exception.GraceException;
import com.geniusk.common.utils.TreeUtil;
import com.geniusk.system.model.mapper.MenuMapper;
import com.geniusk.system.model.pojo.Menu;
import com.geniusk.system.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> selectAllMenu(Menu menu) {
        List<Menu> menus = menuMapper.selectAllMenu(menu);
        if(menus.isEmpty()){
            return new ArrayList<>();
        }
        return buildMenus(menus);
    }

    @Override
    public boolean selectMenuIsExistByMenuIds(Long[] menuIds) {
        return menuMapper.selectMenuIsExistByMenuIds(menuIds);
    }

    @Override
    public int insertMenu(Menu menu) {
        HashMap<String,Object> hashMap = new HashMap<>();
        hashMap.put("menuName",menu.getMenuName());
        hashMap.put("parentId",menu.getParentId());
        if (!menuMapper.selectMenuIsExistByMenuName(hashMap)) {
            GraceException.display(ResponseType.MENU_EXIST_ERROR);
        }
        return menuMapper.insertMenu(menu);
    }

    @Override
    public int updateMenu(Menu menu){
        return menuMapper.updateMenu(menu);
    }

    @Override
    public int deleteMenuByIds(Long[] ids){
        if (!menuMapper.menuCanDeleteOrNot(ids)) {
            GraceException.display(ResponseType.CHILD_NODE_EXIST_ERROR);
        }
        return menuMapper.deleteMenuByIds(ids);
    }

    @Override
    public List<Menu> selectMenuByUserId(HashMap<String,Object> hashMap) {
        List<Menu> menus = new ArrayList<>(menuMapper.selectMenuByUserId(hashMap));
        if(menus.isEmpty()){
            return new ArrayList<>();
        }
        return buildMenus(menus);
    }


    @Override
    public List<String> selectMenuByRoleId(Long roleId) {
        return menuMapper.selectMenuByRoleId(roleId);
    }

    @Override
    public Set<String> selectPermissionByUserId(Long userId) {
        return menuMapper.selectPermissionByUserId(userId);
    }

    private List<Menu> buildMenus(List<Menu> menuList){
        List<Menu> menuTree = new ArrayList<>();
        try{
            menuTree.addAll(TreeUtil.buildTree(menuList, "menuId"));
        }catch(Exception e){
            e.printStackTrace();
        }
        return menuTree;
    }
}
